package com.longcom.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class HttpClientHelper
{
	public static String JSESSIONID = null;
	private static DefaultHttpClient httpClient;
	private static HttpPost httpPost;
	private static HttpResponse httpResponse;
	private static HttpEntity httpEntity;

	public static String postData(String url, List<NameValuePair> pairList)
	{
		httpPost = new HttpPost(url);
		if (pairList != null)
		{
			try
			{
				httpEntity = new UrlEncodedFormEntity(pairList, "utf-8");
				httpPost.setEntity(httpEntity);
				if (JSESSIONID != null)
				{
					httpPost.setHeader("Cookie", "JSESSIONID=" + JSESSIONID);
				}
				BasicHttpParams httpParams = new BasicHttpParams();  
			    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);  //request timeout
			    HttpConnectionParams.setSoTimeout(httpParams, 5000);  // wait for data
			    httpClient = new DefaultHttpClient(httpParams);  
				httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
				{
					HttpEntity httpEntity = httpResponse.getEntity();
					String respStr = EntityUtils.toString(httpEntity, "UTF-8");

					CookieStore mCookieStore = httpClient.getCookieStore();
					List<Cookie> cookies = mCookieStore.getCookies();
					for (int i = 0; i < cookies.size(); i++)
					{
						if ("JSESSIONID".equals(cookies.get(i).getName()))
						{
							JSESSIONID = cookies.get(i).getValue();

							break;
						}

					}
					System.out.println("respStr:" + respStr);

					return respStr;
				}
			} catch (UnsupportedEncodingException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}
}
